package com.citywithincity.api.post;

import java.util.List;
import java.util.Map;

import com.citywithincity.db.Page;
import com.jzoom.caster.Caster;

public class ApiResponse {

	private Map<String, Object> raw;
	private Object result;
	private int flag;
	
	//应该把所有的东西输出来
	
	
	
	public ApiResponse(Map<String, Object> raw){
		this(raw, null, true);
	}
	
	
	public boolean isPage() {
		if(raw instanceof Map) {
			return ((Map)raw).containsKey("page");
		}
		return false;
	}
	
	public ApiResponse(Map<String, Object> raw,Object result,boolean hasFlag){
		this.raw = raw;
		if(hasFlag) {
			this.flag = (Integer) raw.get("flag");
			this.result = raw.get("result");
		}else {
			this.result = result;
		}
		
	}
	
	/**
	 * 
	 * @param key
	 * @return
	 */
	public String getString(String key){
		return Caster.to(get(key), String.class);
	}
	
	
	@SuppressWarnings("unchecked")
	private Object get(String key){
		if(result==null)return null;
		if(result instanceof Map){
			return ((Map<String, Object>)result).get(key);
		}
		throw new RuntimeException("尝试从非Map中获取数据");
	}
	
	/**
	 * 获取int，注意这里null会自动转为0，所以如果需要获取null使用{@see com.citywithincity.api.post.ApiResponse#getInteger}
	 * @param key
	 * @return
	 */
	public int getInt(String key){
		return Caster.to(get(key), int.class);
	}
	
	public Integer getInteger(String key){
		return Caster.to(get(key), Integer.class);
	}
	
	public boolean getBool(String key){
		return Caster.to(get(key), boolean.class);
	}
	

	public Boolean getBoolean(String key){
		return Caster.to(get(key), Boolean.class);
	}
	
	public String getString(){
		if(result==null)return null;
		return String.valueOf(result);
	}
	
	@Override
	public String toString() {
		return raw.toString();
	}
	
	@SuppressWarnings("unchecked")
	public List<Object> getList(){
		if(result==null)return null;
		return (List<Object>)result;
	}
	
	@SuppressWarnings("unchecked")
	public Map<String, Object> getMap(){
		if(result==null)return null;
		List<Object> list = (List<Object>)result;
		if(list.size()==0)return null;
		return (Map<String, Object>)list.get(0);
	}
	
	public boolean isSuccess(){
		return flag == 0;
	}
	
	
	
	@SuppressWarnings("unchecked")
	public <T> T get(){
		return (T)  raw.get("result");
	}
	
	
	public <T> T get(Class<T> classOfT){
		return Caster.to(raw.get("result"),classOfT);
	}

	public <T> Page<T> toPage(){
		return new Page<T>();
	}
	
	
	public String getError(){
		return (String) raw.get("result");
	}


	public int getFlag() {
		return flag;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Map<String, Object> getMap(String key) {
		if(result == null) {
			return null;
		}
		if(result instanceof Map) {
			return (Map) ((Map)result).get(key);
		}
		return null;
	}



	public Map<String, Object> getRaw() {
		return raw;
	}



	public void setRaw(Map<String, Object> raw) {
		this.raw = raw;
	}
	
}
